import re
from fastapi import FastAPI, File, UploadFile, Request, Form
from PIL import Image
import io
import numpy as np
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
from wxauto import WeChat
from paddleocr import PaddleOCR
import cv2

mag = FastAPI()
wx = WeChat()
#输入关键词
@mag.post("/zhaunhuan")
async def mmag(file: UploadFile = File(...), keyword: str = Form(...),group_name: str = Form(...)):
    try:
        connect = await file.read()
        image = Image.open(io.BytesIO(connect))
        image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)

        ocr = PaddleOCR(use_angle_cls=True, lang='ch', show_log=False, det_db_thresh=0.3, det_db_box_thresh=0.5)
        result = ocr.ocr(image_cv, cls=True)
        # print(result[0])
        result_z=result[0]      

        #输入关键词
        if keyword:
            textds=[]
            error_range = 10
            for res_num in range(len(result_z)-1):
                y_num=result_z[res_num][0][0][1]
                next_y_num=result_z[res_num+1][0][0][1]
                if abs(next_y_num-y_num) < error_range:
                    textds.append([result_z[res_num][1][0],result_z[res_num+1][1][0]])
            print(textds)
                
            a = []
            chinese_txt = []

            for line in textds:
                for word in line:
                    line_text = word
                    print(line_text)
                    if keyword in line_text:
                        a.append(line)
            print(a)

            for line in a:
                for word_info in line:
                    text = word_info
                    fields = text.split()
                    for field in fields:
                        field = str(field)
                        chinese_text = re.sub(r'[^\u4e00-\u9fff]', '', field)  # 只保留中文字符
                        if chinese_text:
                            chinese_txt.append(chinese_text)

            chinese_texts=[]
            for name in chinese_txt:
                if keyword not in name:
                    chinese_texts.append(name)

            wx.ChatWith(group_name)
            msgs = wx.GetGroupMembers()

            fit_nemes=[]

            for image_name in chinese_texts:
                for group_need in msgs:
                    if image_name in group_need:
                        fit_nemes.append(image_name)
            return {"names": fit_nemes}
        
        #不输入关键词
        else:
            chinese_texts = []
            for line in result:
                for word_info in line:
                    selc = word_info[1][0]
                    split_names = selc.split()
                    # 遍历 split_names 列表中的每个字符串元素
                    for name in split_names:
                        chinese_x = re.sub(r'[^\u4e00-\u9fff]', '', name)
                        if chinese_x:
                            chinese_texts.append(chinese_x)

            wx.ChatWith(group_name)
            msgs = wx.GetGroupMembers()

            fit_nemes=[]

            for image_name in chinese_texts:
                for group_need in msgs:
                    if image_name in group_need:
                        fit_nemes.append(image_name)
            return {"names": fit_nemes}

    except Exception as e:
        print(f"处理图片时出错: {e}")
        return {"status": "error", "message": f"处理图片时出错: {e}"}


@mag.post("/send_wechat")
async def send_wechat(request: Request):
    try:
        data = await request.json()
        chinese_texts = data.get("names", [])  # 获取前端传递的人名列表
        group_name = data.get("group_name")
        message = data.get("message")
        if not group_name or not message:
            return {"status": "error", "message": "群名称和消息内容不能为空"}
            
        wx.ChatWith(group_name)
        msgs = wx.GetGroupMembers()

        valid_names = []

        for image_name in chinese_texts:
            for group_need in msgs:
                if image_name in group_need:
                    valid_names.append(group_need)
        print("群昵称")
        print(valid_names)

        wx.SendMsg(msg=message, who=group_name, at=valid_names)
        return {"status": "success", "message": "消息已发送"}
    except Exception as e:
        print(f"发送微信消息时出错: {e}")
        return {"status": "error", "message": f"发送微信消息时出错: {e}"}


mag.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_methods=["*"],  # 允许所有方法（GET、POST 等）
    allow_headers=["*"],  # 允许所有请求头
)

if __name__ == '__main__':
    uvicorn.run("__main__:mag", host="0.0.0.0", port=8000)